﻿using System;
using System.Collections.Generic;
using System.Text;

namespace JESAI.Common.Util
{
    public class IDCardConvert
    {

        /// <summary>
        /// 转换15位身份证号码为18位
        /// </summary>
        /// <param name="oldIDCard">15位的身份证</param>
        /// <returns>返回18位的身份证</returns>
        public static string IDCard15To18(string oldIDCard)
        {
            int iS = 0;

            //加权因子常数
            int[] iW = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            //校验码常数
            string LastCode = "10X98765432";
            //新身份证号
            string newIDCard;

            newIDCard = oldIDCard.Substring(0, 6);
            //填在第6位及第7位上填上‘1’，‘9’两个数字
            newIDCard += "19";

            newIDCard += oldIDCard.Substring(6, 9);

            //进行加权求和
            for (int i = 0; i < 17; i++)
            {
                iS += int.Parse(newIDCard.Substring(i, 1)) * iW[i];
            }

            //取模运算，得到模值
            int iY = iS % 11;
            //从LastCode中取得以模为索引号的值，加到身份证的最后一位，即为新身份证号。
            newIDCard += LastCode.Substring(iY, 1);
            return newIDCard;
        }

        /// <summary>
        /// 18为降15
        /// </summary>
        /// <param name="oldIDCard"></param>
        /// <returns></returns>
        public static string IDCard18To15(string oldIDCard)
        {
            if (oldIDCard.Length != 18)
                return oldIDCard;
            oldIDCard = oldIDCard.Remove(17, 1);
            oldIDCard = oldIDCard.Remove(6, 2);
            return oldIDCard;
        }
    }
}
